#! python3
# 用csv模块处理CSV文件

import csv


def readCSV(filename):
    """
    从 Reader 对象读取数据
    :param filename:
    :return:
    """
    csvFile = open(filename, encoding='utf-8')
    csvReader = csv.reader(csvFile)
    csvData = list(csvReader)
    print(csvData)
    csvFile.close()

    # Reader对象只能循环遍历一次。要再次读取文件，必须调用csv.reader，创建一个对象。
    csvFile = open(filename, encoding='utf-8')
    csvReader = csv.reader(csvFile)
    for row in csvReader:
        print('Row #' + str(csvReader.line_num) + ' ' + str(row))
        # for column in row:
        #     print(column, " ", end="")
        # print()
    csvFile.close()


def writeCSV(filename, operator, dataList, *delimiter):
    """
    将数据写入 CSV 文件
    :param filename: 文件名
    :param operator: w-写，a-追加
    :param dataList: 要写入的数据
    :param delimiter: 分隔符
    :return:
    """
    #  如果忘记了 newline=''，CSV 文件将有两倍行距
    csvFile = open(filename, operator, encoding='utf-8', newline="")
    # 单元格之间的字符为制表符，有两倍行距
    # csvWriter = csv.writer(csvFile, delimiter='\t', lineterminator='\n\n')
    if len(delimiter) == 1:
        csvWriter = csv.writer(csvFile, delimiter=delimiter[0])
    else:
        csvWriter = csv.writer(csvFile)
    for row in dataList:
        csvWriter.writerow(row)
    csvFile.close()


if __name__ == '__main__':

    readCSV('file/example.csv')

    # list1 = ['spam', 'eggs', 'bacon', 'ham']
    # list2 = ['Hello, world!', 1, 2, 3.141592, '你好']
    # writeCSV('file/output.csv', 'w', [list1, list2])
    # writeCSV('file/output1.csv', 'w', [list1, list2], "|")
